package com.baselib.libnetwork.net;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.baselib.libnetwork.BuildConfig;
import com.baselib.libnetwork.net.request.GetRequest;
import com.baselib.libnetwork.net.request.PostRequest;
import com.baselib.libnetwork.net.simpledown.DownloadCallback;
import com.baselib.libnetwork.net.simpledown.DownloadUtil;
import com.baselib.libnetwork.net.utils.HttpLogger;
import com.baselib.libnetwork.net.utils.HttpsUtils;
import com.baselib.libnetwork.net.utils.TLSSocketFactory;


import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

import okhttp3.Call;
import okhttp3.OkHttpClient;

/**
 * @author lixuce
 * @version v1.0
 * @description
 * @since 2017/10/29
 */

public class HttpManager {
    public static final long DEFAULT_MILLISECONDS = 60000;      //默认的超时时间
    private Handler mDelivery;

    private OkHttpClient okHttpClient;      //ok请求的客户端

    public HttpManager() {
        mDelivery = new Handler(Looper.getMainLooper());
    }

    public static HttpManager getInstance() {
        return OkGoHolder.holder;
    }

    private static class OkGoHolder {
        private static HttpManager holder = new HttpManager();
    }
    public static HashMap<Object, Call> clientHashMap = new HashMap<Object, Call>();
    public static List<Object> clientCancle = new ArrayList<>();
    private static Map<String, String> commonParam = new HashMap<>();
    private static String commonParamStr;

    public Handler getDelivery() {
        return mDelivery;
    }

    public OkHttpClient okHttp() {
        if (okHttpClient == null) {
            HttpLogger loggingInterceptor = new HttpLogger("pie_log_netWork");
            loggingInterceptor.setPrintLevel(HttpLogger.Level.BODY);
            loggingInterceptor.setColorLevel(Level.INFO);

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.retryOnConnectionFailure(true);
            builder.readTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
            builder.writeTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
            builder.connectTimeout(DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
            builder.hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier);

            // !!! release包测试，添加LOG打印
//            HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
//            builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
//            builder.addInterceptor(loggingInterceptor);
//            builder.addNetworkInterceptor(new StethoInterceptor());
            HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
            builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
            builder.addInterceptor(loggingInterceptor);
            if (BuildConfig.DEBUG) {

//                builder.addNetworkInterceptor(new StethoInterceptor());
            } else {
                sslv3(builder);
            }

            okHttpClient = builder.build();
        }
        return okHttpClient;
    }

    private void sslv3(OkHttpClient.Builder builder) {
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
            try {
                sslContext.init(null, null, null);
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        SSLSocketFactory socketFactory = new TLSSocketFactory(sslContext.getSocketFactory());
        builder.sslSocketFactory(socketFactory, HttpsUtils.UnSafeTrustManager);
    }


    /**
     * get请求
     */
    public static GetRequest getOther(String url) {
        return new GetRequest(appendUrlParams(url));
    }

    /**
     * get请求
     */
    public static GetRequest get(String url) {
        return new GetRequest(url);
    }

    /**
     * post请求
     */
    public static PostRequest postOther(String url) {
        return new PostRequest(appendUrlParams(url));
    }

    /**
     * get请求
     */
    public static PostRequest post(String url) {
        return new PostRequest(url);
    }


    public static void removeUrlParams(String... key) {
        if (commonParam != null && commonParam.size() > 0) {
            for (String s : key) {
                commonParam.remove(s);
            }
        }
        commonParamStr = null;
        appStr();
    }

    public static void removeUrlParam(String key) {
        if (commonParam != null && commonParam.size() > 0) {
            commonParam.remove(key);
        }
        commonParamStr = null;
        appStr();
    }

    public static void setCommonParams(Map<String, String> map) {
        commonParamStr = null;
        commonParam = map;
        appStr();
    }

    public static void addUrlParams(String key, String value) {
        commonParamStr = null;
        commonParam.put(key, value);
        appStr();
    }


    private static String appendUrlParams(String url) {
        String urlParams = new String(url + "?");

        if (urlParams.contains(" ")) {
            urlParams = urlParams.replace(" ", "").trim();
        }
        appStr();
        return urlParams + commonParamStr;
    }

    private static void appStr() {
        StringBuffer stringBuffer = new StringBuffer();
        if (TextUtils.isEmpty(commonParamStr)) {
            for (Map.Entry<String, String> entry : commonParam.entrySet()) {
                stringBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }

            String commonUrl = stringBuffer.toString();
            if (commonUrl.endsWith("&")) {
                commonUrl = commonUrl.substring(0, commonUrl.length() - 1);
            }
            commonParamStr = commonUrl;
        }
    }

    /**
     * 根据Tag取消请求
     */
    public void cancelTag(Object tag) {
        if (tag == null) {
            return;
        }
        for (Call call : okHttp().dispatcher().queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
        for (Call call : okHttp().dispatcher().runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }
    public static void cancelDownloadByTag(Object tag) {
       DownloadUtil.cancelByTag(tag);
    }
    public static void download(String url, String path,DownloadCallback callback) {
        DownloadUtil.download(url, path,callback);
    }

    public static void downloadSong(String url, String path, Object tag,DownloadCallback callback) {
        DownloadUtil.downloadSong(url, path, tag,callback);
    }
}
